package cn.itcast.cd.action.interceptor;

import java.util.List;
import java.util.Set;

import org.apache.struts2.ServletActionContext;

import cn.itcast.cd.domain.Permission;
import cn.itcast.cd.domain.User;
import cn.itcast.cd.service.IPermissionService;
import cn.itcast.cd.service.ISecretService;
import cn.itcast.cd.utils.SessionUtils;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SecretInterceptor extends AbstractInterceptor {

	private ISecretService secretService;
	private IPermissionService permissionService;
	
	
	
	public void setPermissionService(IPermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public void setSecretService(ISecretService secretService) {
		this.secretService = secretService;
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		
		// -1:得到当前访问的是哪个ACTION.
		Action action = (Action) invocation.getAction();
		String actionName = action.getClass().getName();
		
		
		//-2:再得到当前访问的是ACTION的具体的哪个方法.
		String methodName = invocation.getProxy().getMethod();
		
		String resourceName = actionName+"."+methodName;
		//System.out.println("--------看一下拦截器中资源的名字.-----------------"+resourceName);
		
		
		//先查一下,请求的资源是否是被权限管理的.
		Permission permission  =secretService.getPermissionByName(resourceName);
		 
		//这里做一下优化处理:一执行这个拦截器,将所有的权限查出来.放在一个MAP中.以后就不用查了.
		/*List<Permission> permissions = SessionUtils.getPermissionInSession();
		if(permissions==null || permissions.size()==0){
			permissions = permissionService.queryEntity("FROM Permission", null);
			SessionUtils.setPermissionInSession(permissions);
		}
		
		for (Permission permission2 : permissions) {
			if(resourceName.equals(permission2.getResource())){
				System.out.println(permission2);
				User user = SessionUtils.getUserInSession();
				if(user!=null){
					Set<Permission> userPermissions = secretService.getPermissionByUser(user);
					//System.out.println(userPermissions);
					System.out.println(userPermissions.contains("--------看是否包含------------"+permission2));
					if(!userPermissions.contains(permission2)){
						return "Forbidden";
					}
				}
				
			}
		}
		return invocation.invoke();*/
		
		//System.out.println("------看一下请求的资源是否需要权限-------"+permission);
		if(permission!=null){
			//-3:再得到用户,在查看这个用户有没有权限查看请求的资源.
			User user = SessionUtils.getUserInSession();
			
			//-4:这里要判断一下用户是否为空.虽然一般要用户登陆了之后才会进行资源的访问,但如果SESSION时间超期,就会报错的.
			if(user!=null){
				Set<Permission> ps= secretService.getPermissionByUser(user);
				if(ps==null || !ps.contains(permission)){
					return "Forbidden";
				}
			}
		}
		
		return invocation.invoke();
	}

}
